Imports System.Data.Common
Imports System.Globalization
Partial Class Presentation_Workflow
    Inherits System.Web.UI.Page


    Protected Sub txtSearchName_Change(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearchName.TextChanged
        PopulateClientDrop()
        Success.Visible = False

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Page.Title = "Daily Report Entry"

        If Not Page.IsPostBack Then

            Dim Sql As String
            Dim FirstProject As New ListItem
            Dim FirstStatus As New ListItem
            Dim UName As String
            Dim Records As DbDataReader
            Dim Travel As New Hashtable


            UName = Request.Cookies("Profile").Item("ExecutiveUserName")

            Page.Title = "Daily Report Entry"

            PopulateClientFirst()

            'Populate the Project dropdownlist
            Sql = "Select ProjectID, ProjectName FROM ProjectMaster" & _
                    " WHERE Completed = 0 ORDER BY ProjectName"
                

            Records = GenHelper.ExecuteReader(Sql, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())
            FirstProject.Text = "Select a Project"
            FirstProject.Value = "0"
            FirstProject.Selected = True
            dlProjectNames.DataTextField = "ProjectName"
            dlProjectNames.DataValueField = "ProjectID"
            dlProjectNames.DataSource = Records
            dlProjectNames.DataBind()
            dlProjectNames.Items.Add(FirstProject)
            Records.Close()

            'Populate the Action Taken dropdownlist
            Sql = "SELECT ActionID, ActionDescription FROM ActionMaster ORDER BY ActionID"
            Records = GenHelper.ExecuteReader(Sql, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())
            dlActionTaken.DataTextField = "ActionDescription"
            dlActionTaken.DataValueField = "ActionID"
            dlActionTaken.DataSource = Records
            dlActionTaken.DataBind()
            Records.Close()

            'Populate the Travel mode dropdownlist
            Travel.Add("Own Vehicle", "Own Vehicle")
            Travel.Add("Auto", "Auto/Taxi")
            Travel.Add("Public Transport", "Public Transport")
            Travel.Add("Other", "Other")

            dlTravelMode.DataTextField = "value"
            dlTravelMode.DataValueField = "key"
            dlTravelMode.DataSource = Travel
            dlTravelMode.DataBind()

            'Populate the Status dropdownlist
            Sql = "Select StatusID, StatusDescription from StatusMaster order by StatusDescription"
            Records = GenHelper.ExecuteReader(Sql, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())
            FirstStatus.Text = "Select a Status"
            FirstStatus.Value = "0"
            FirstStatus.Selected = True
            dlStatus.DataValueField = "StatusID"
            dlStatus.DataTextField = "StatusDescription"
            dlStatus.DataSource = Records
            dlStatus.DataBind()
            dlStatus.Items.Add(FirstStatus)
            Records.Close()

        End If



    End Sub

    Protected Sub PopulateClientDrop()

        Dim Sql As String
        Dim UID As Integer
        Dim Records As DbDataReader
        'Dim Params As New Hashtable
        Dim First As New ListItem
        Dim Params(0) As GenParameter

        If txtSearchName.Text = "" Then
            PopulateClientFirst()
            Return
        End If


        UID = Request.Cookies("Profile").Item("ExecutiveID")

        Sql = "Select CompanyAssignments.ClientID AS 'ClientID', ClientMaster.ClientName AS 'ClientName' from CompanyAssignments INNER JOIN ClientMaster" & _
        " ON ClientMaster.ClientID = CompanyAssignments.ClientID" & _
        " WHERE ClientMaster.ClientName LIKE CONCAT('%',?ClientName,'%') AND CompanyAssignments.ExecutiveID = " & UID & _
        " ORDER BY ClientMaster.ClientName"

        'Params.Add("?ClientName", txtSearchName.Text.ToString)
        Params(0) = New GenParameter("?ClientName", txtSearchName.Text, Data.DbType.String)

        Records = GenHelper.ExecuteReader(Sql, Params, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())

        dlClientNames.Items.Clear()
        First.Text = "Select a Client"
        First.Value = "0"
        First.Selected = True
        dlClientNames.DataSource = Records
        dlClientNames.DataBind()
        dlClientNames.Items.Add(First)
        Records.Close()

    End Sub


    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim Sql As String
        Dim RightNow As Date
        Dim Params(8) As GenParameter
        Dim TDate As String
        Dim LastInsertedID As Integer
        Dim DateofNextAction As String
        Dim ArraySplit(2) As String


        RightNow = Now.AddHours(10)
        RightNow = RightNow.AddMinutes(30)
        TDate = RightNow.Year & "/" & RightNow.Month & "/" & RightNow.Day


        If Not Page.IsValid Then
            Success.Visible = False
            Exit Sub
        End If

        ArraySplit = txtDateofNextAction.Text.Split("/")

        DateofNextAction = ArraySplit(2) & "/" & ArraySplit(1) & "/" & ArraySplit(0)

        'Make the entry into workflow

        Sql = "INSERT INTO WorkflowMaster (ExecutiveID, ProjectID, MeetingDate, ClientID,  Details, ActionID, NextAction, DateofNextAction, StatusID)" & _
        " VALUES (?EID, ?PID, ?TDATE, ?CID, ?REMARKS, ?ACTIONID, ?NEXTACTION, ?DATEOFNEXTACTION, ?HOTWARMCOLD)" & _
        " ;Select LAST_INSERT_ID() AS Id"

        Params(0) = New GenParameter("?EID", Request.Cookies("Profile").Item("ExecutiveID"), Data.DbType.UInt16)
        Params(1) = New GenParameter("?PID", dlProjectNames.SelectedValue, Data.DbType.UInt32)
        Params(2) = New GenParameter("?TDate", TDate, Data.DbType.Date)
        Params(3) = New GenParameter("?CID", dlClientNames.SelectedValue, Data.DbType.UInt32)
        Params(4) = New GenParameter("?REMARKS", txtDetails.Text, Data.DbType.String)
        Params(5) = New GenParameter("?ACTIONID", dlActionTaken.SelectedValue, Data.DbType.UInt16)
        Params(6) = New GenParameter("?NEXTACTION", txtNextAction.Text, Data.DbType.String)
        Params(7) = New GenParameter("?DATEOFNEXTACTION", DateofNextAction, Data.DbType.Date)
        Params(8) = New GenParameter("?HOTWARMCOLD", dlStatus.SelectedValue, Data.DbType.UInt16)


        'Execute the Insert, and get the Last Inserted ID
        LastInsertedID = GenHelper.ExecuteScalar(Sql, Params, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())

        'Make an entry in Distance Travelled

        If dlActionTaken.SelectedItem.Text = "Met" Then


            Sql = "INSERT INTO DistanceTravelled (InteractionID, Distance, ModeofTravel)" & _
            " VALUES (?LastInsertedID, ?Distance, ?TravelMode)"

            ReDim Params(2)

            Params(0) = New GenParameter("?Distance", txtKmsTravelled.Text, Data.DbType.UInt16)
            Params(1) = New GenParameter("?TravelMode", dlTravelMode.SelectedValue, Data.DbType.String)
            Params(2) = New GenParameter("?LastInsertedID", LastInsertedID, Data.DbType.UInt64)

            GenHelper.ExecuteNonQuery(Sql, Params, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())

        End If

        'Code to clear the fields
        txtSearchName.Text = ""
        dlClientNames.SelectedValue = 0
        dlProjectNames.SelectedValue = 0
        dlActionTaken.SelectedValue = 1
        dlTravelMode.SelectedValue = "Own Vehicle"
        txtKmsTravelled.Text = ""
        txtDetails.Text = ""
        dlStatus.SelectedValue = 0
        txtNextAction.Text = ""
        txtDateofNextAction.Text = ""
        CalendarPick.SelectedDate = #12:00:00 AM#
        Success.Visible = True


    End Sub

    Protected Sub cvdtxtDateofNextAction_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)

        Dim Day As Integer
        Dim Month As Integer
        Dim Year As Integer
        Dim IsLeap As Boolean
        Dim FullDate As Date
        Dim RightNow As Date
        Dim DateArray As Array
        Dim culture As CultureInfo = New CultureInfo("hi-IN", True)

        If Not vdtxtDateofNextAction.IsValid Then
            Exit Sub
        End If

        RightNow = Now.AddHours(10)
        RightNow = RightNow.AddMinutes(30)

        DateArray = txtDateofNextAction.Text.Split("/")

        'Code to check the validity of the date


        Day = DateArray(0)
        Month = DateArray(1)
        Year = DateArray(2)

        'Check Date Validity

        If (Day < 1 Or Day > 31) Then
            cvdtxtDateofNextAction.ErrorMessage = "Day must be between 1 and 31"
            args.IsValid = False
            Return
        End If

        If (Month < 1 Or Month > 12) Then
            cvdtxtDateofNextAction.ErrorMessage = "Month must be between 1 and 12"
            args.IsValid = False
            Return
        End If

        If ((Month = 4 Or Month = 6 Or Month = 9 Or Month = 11) And Day = 31) Then
            cvdtxtDateofNextAction.ErrorMessage = "Month " & Month & "doesn't have 31 days!"
            args.IsValid = False
            Return
        End If

        If (Month = 2) Then

            'Check for February 29th
            IsLeap = (Year Mod 4 = 0 And (Year Mod 100 <> 0 Or Year Mod 400 = 0))

            If (Day > 29 Or (Day = 29 And IsLeap = False)) Then
                cvdtxtDateofNextAction.ErrorMessage = "February " & Year & " doesn't have " & Day & " days!"
                args.IsValid = False
                Return

            End If


        End If

        'Check if it's a Sunday
        FullDate = Date.Parse(Day & "/" & Month & "/" & Year, culture)

        If FullDate.DayOfWeek = DayOfWeek.Sunday Then
            cvdtxtDateofNextAction.ErrorMessage = "Date of Next Action Cannot be a Sunday"
            args.IsValid = False
        End If

        'Check if the date is before today's date

        If FullDate.Date <= RightNow.Date And Not txtNextAction.Text.ToLowerInvariant.Contains("nothing") Then
            cvdtxtDateofNextAction.ErrorMessage = "Date of Next Action cannot be lesser than or equal to today!" & _
            " If there is no further action, please mention the word 'Nothing' in your Next Action Box first"
            args.IsValid = False
        End If

    End Sub

    Protected Sub ValidateKms(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)

        'Check if the Expression is valid. If not, then don't display the required text.

        If vdtxtKmsTravelled.IsValid = False Then
            args.IsValid = True
            Return
        End If

        If dlActionTaken.SelectedItem.Text = "Met" And txtKmsTravelled.Text = "" Then
            args.IsValid = False
        Else
            args.IsValid = True
        End If

    End Sub

    Protected Sub PopulateClientFirst()

        Dim FirstClient As New ListItem

        dlClientNames.Items.Clear()
        FirstClient.Text = "Select a Client"
        FirstClient.Value = "0"
        FirstClient.Selected = True
        dlClientNames.Items.Add(FirstClient)

    End Sub
End Class
